<template>
  <div class="login">
    <div class="login-component">
      <div class="component">
        <div class="login-container">
          <div class="container-left">
            <div class="logoBox">
              <div>
                <img style="width: 175px" src="@/assets/images/logo.png"/>
                <div class="logo-title">
                  {{ state.platformInfo.chineseName }}
                </div>
              </div>
              <img
                  src="@/assets/images/login.png"
                  style="width: 400px"
                  class="nlogo_logo"
              />
            </div>
          </div>
          <div class="container-right">
            <div class="login-form">
              <p class="login-text mb-30px f_w_normal">欢迎登录</p>
              <el-form
                  ref="loginFormRef"
                  layout="horizontal"
                  :model="state.LoginForm"
                  :rules="state.rules"
                  @submit.native.prevent="
                  () => {
                    handleSubmit(loginFormRef);
                  }
                "
              >
                <el-form-item>
                  <el-input
                      v-model="state.LoginForm.loginName"
                      @keyup.enter.native="
                      () => {
                        handleSubmit(loginFormRef);
                      }
                    "
                      placeholder="请输入账号"
                  />
                </el-form-item>
                <el-form-item>
                  <el-input
                      v-model="state.LoginForm.password"
                      type="password"
                      @keyup.enter.native="
                      () => {
                        handleSubmit(loginFormRef);
                      }
                    "
                      placeholder="请输入密码"
                      autocomplete="new-password"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <div class="Verification_code_box">
                    <el-input
                        v-model="state.LoginForm.verifyCode"
                        placeholder="请输入验证码"
                        @keyup.enter.native="
                        () => {
                          handleSubmit(loginFormRef);
                        }
                      "
                        class="input-with-code"
                        :maxlength="4"
                    >
                      <template #append>
                        <img
                            :src="state.captcha"
                            class="absolute right-0 h-full cursor-pointer"
                            @click="setCaptcha"
                        />
                      </template>
                    </el-input>
                  </div>
                </el-form-item>
                <el-form-item>
                  <el-button
                      type="submit"
                      :loading="state.loading"
                      class="login-submit"
                      @click="
                      () => {
                        handleSubmit(loginFormRef);
                      }
                    "
                  >
                    登录
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>

      <p class="company_name">
        <span class="copyright">{{ state.platformInfo.keepOnRecord }}</span>
      </p>
      <p
          v-if="state.platformInfo.technicalSupport.length > 0"
          class="company_name"
      >
        {{ state.platformInfo.technicalSupport }}
      </p>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import {userLoginApi} from "@/api/user";
import {useRoute, useRouter} from "vue-router";
import {
  CONFIGURE_KEY,
  ROUTER_RESOURCES,
  USER_INFO_KEY,
} from "@/utils/enums/cache-enum";
import {Storage} from "@/utils/storage";
import {useStore} from "@/store/baseData/index";
import {monitor} from "@/assets/script/menus/monitor";
import {middle} from "@/assets/script/menus/middle";
import {number} from "@intlify/core-base";

const router = useRouter();
const route = useRoute();
const store = useStore();
const loginFormRef = ref<FormInstance>();
const state = reactive({
  loading: false,
  captcha: "" as string,
  code: "" as string,
  /* 平台基础信息 */
  platformInfo: {
    chineseName: "琅智监控设备管理中台",
    englishName: "LANGZHI INTELLIGENT HEALTH MANAGEMENT PLATFORM",
    /* 备案 */
    keepOnRecord:
        "成都乐享智家科技有限责任公司 Copyright @2017-" +
        new Date().getFullYear(),
    /* 备案号 */
    keepOnRecordNum: "蜀ICP备16033182号",
    /* 技术支持 */
    technicalSupport: "",
  },
  LoginForm: {
    loginName: "test.test",
    password: "lzzhyl123456",
    verifyCode: "",
  },
  rules: {
    loginName: [{required: true, message: "账号不能为空", trigger: "change"}],
    password: [
      {required: true, message: "密码不能为空", trigger: "change"},
      {min: 6, max: 16, message: "请输入6-16位密码", trigger: "change"},
    ],
    verifyCode: [
      {required: true, message: "验证码不能为空", trigger: "change"},
      {min: 4, max: 4, message: "请输入4位验证码", trigger: "change"},
    ],
  },
});

onMounted(() => {
  const tabs = document.getElementsByClassName("tabs-view-content");
  if (tabs) {
    tabs[0].setAttribute("style", "padding: 0 !important;");
  }
});

const setCaptcha = async () => {
  state.code = Math.random().toString().trim();
  let randomCode = Math.random();
  state.captcha = `/security/verify/code?number=${state.code}&randomCode=${randomCode}`;
};

/**
 * 登录
 * @param formEl 参数
 */
const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  const {loginName, password, verifyCode} = state.LoginForm;
  if (!loginName || !password) {
    ElMessage.warning("账号或密码不能为空！");
    return;
  }
  if (!verifyCode || verifyCode.length != 4) {
    ElMessage.warning("验证码不能为空！");
    return;
  }
  state.loading = true;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const params: any = state.LoginForm;
      params["number"] = state.code.toString();
      userLoginApi(params)
          .then((res) => {
            console.log("userLogin", res);
            if (res.code === 0) {
              const data = res.data;
              // 资源
              const resourceList = data.resourceList;

              if (window.location && window.location.hostname) {
                let hostname = window.location.hostname
                if (hostname != 'middle.lzzhyl.com') {
                  // 设备路由（监控平台）
                  Storage.set(ROUTER_RESOURCES, monitor);
                } else {
                  // 设备路由（中台平台）
                  Storage.set(ROUTER_RESOURCES, middle);
                }
              }
              data.resourceList = [];
              // 配置信息
              const configureList = data.configureList;
              Storage.set(CONFIGURE_KEY, configureList);
              data.configureList = [];
              // 用户信息
              Storage.set(USER_INFO_KEY, data);
              store.addDynamicRoute();

              ElMessage({
                type: "success",
                message: "登录成功！",
                onClose: () => {
                  router.replace((route.query.redirect as string) ?? "/home");
                },
              });
            }
          })
          .finally(() => {
            state.loading = false;
            state.LoginForm.verifyCode = "";
            setCaptcha();
          });
    } else {
      state.loading = false;
      console.log("error submit!", fields);
    }
  });
};

setCaptcha();
</script>
